<?php

namespace app\third\controller;

use app\common\model\Alipay;
use app\common\model\Wxpay;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\facade\Log;

class Pay extends \app\BaseController
{
    /**
     * H5在线支付.
     */
    public function h5()
    {
        $orderId = input('ak');
        $payLog = Db::name('pay_log')
            ->where('order_id', $orderId)
            ->find();
        if (empty($payLog)) {
            View::assign('message', '订单号有误');

            return View::fetch('failed');
        }
        if ($payLog['status'] == 2) {
            return View::fetch('success');
        }

        try {
            if ($payLog['pay_channel'] == PAY_ALIPAY) {
                View::assign('message', '不支持支付宝支付');
                return View::fetch('failed');

                $pay = new Alipay();

                return $pay->wap([
                    'name' => '话费充值 ' . fen2yuan($payLog['amount']) . ' 元',
                    'out_trade_no' => $orderId,
                    'total_amount' => $payLog['sale_price'],   // 单位：分
                    // 'return_url' => $payLog['return_url'],
                    'return_url' => Request::domain() . '/third/pay/h5/?ak=' . $orderId,
                ]);
            } else {
                $key = 'wxpay_lock_key_' . $orderId;
                $val = cache($key);
                if ($val) {
                    View::assign('message', '支付已取消' . $orderId);

                    return View::fetch('failed');
                }
                cache($key, 1, 60);

                // 微信支付
                $pay = new Wxpay(0, 'wechat_mweb');
                $res = $pay->create([
                    'body' => '话费充值 ' . fen2yuan($payLog['amount']) . ' 元',
                    'out_trade_no' => $orderId,
                    'total_fee' => $payLog['sale_price'],
                    'spbill_create_ip' => Request::ip(),
                    'trade_type' => $payLog['trade_type'],
                ]);
                if (!isset($res['return_code']) || $res['return_code'] != 'SUCCESS') {
                    log::write($res, 'error');
                    $message = $res['return_msg'] ?? '订单生成失败，请稍后再试';
                    view::assign('message', $message);

                    return view::fetch('failed');
                }
                if (!isset($res['result_code']) || $res['result_code'] != 'SUCCESS') {
                    Log::write($res, 'error');
                    $message = $res['err_code_des'] ?? '订单生成失败，请稍后再试！';
                    view::assign('message', $message);

                    return view::fetch('failed');
                }
                $redirectUrl = Request::domain() . '/third/pay/result/?ak=' . $orderId;
                $res['mweb_url'] .= '&redirect_url=' . urlencode($redirectUrl);
                View::assign('url', $res['mweb_url']);

                return View::fetch('redirect');
            }
        } catch (\Exception $e) {
            View::assign('message', $e->getMessage());

            return View::fetch('failed');
        }

        return View::fetch('success');
    }

    /**
     * Array
(
    [return_code] => SUCCESS
    [return_msg] => OK
    [result_code] => SUCCESS
    [mch_id] => 1612953108
    [appid] => wx687b05bc3629d239
    [openid] => oqOlq6YiwIPORkgqGUaGtwYEUNxc
    [is_subscribe] => N
    [trade_type] => MWEB
    [trade_state] => SUCCESS
    [bank_type] => OTHERS
    [total_fee] => 4750
    [fee_type] => CNY
    [cash_fee] => 4750
    [cash_fee_type] => CNY
    [transaction_id] => 4200001301202112161611436247
    [out_trade_no] => 21121614103427994
    [attach] => 
    [time_end] => 20211216141044
    [trade_state_desc] => 支付成功
    [nonce_str] => 1RXTeoyKpMidOmxI
    [sign] => 755597A7A8711AAF7DF1C1D4F1380212
)

Array
(
    [return_code] => SUCCESS
    [return_msg] => OK
    [result_code] => SUCCESS
    [mch_id] => 1612953108
    [appid] => wx687b05bc3629d239
    [device_info] => 
    [trade_state] => NOTPAY
    [total_fee] => 4900
    [out_trade_no] => 21121614022852710
    [trade_state_desc] => 订单未支付
    [nonce_str] => wWtOcuaQQRpVkYCY
    [sign] => 0745DD24936640B829AC0CCFA151A4A8
)
     */
    public function result()
    {
        $orderId = input('ak');
        $payLog = Db::name('pay_log')
            ->field('status')
            ->where('order_id', $orderId)
            ->find();
        if (empty($payLog)) {
            View::assign('message', '订单号有误');

            return View::fetch('failed');
        }

        if ($payLog['status'] == 2) {
            return View::fetch('success');
        }

        $q = input('q');
        if (empty($q)) {
            $url = $this->request->url(true);
            View::assign('url', $url);

            return View::fetch('paying');
        }

        $pay = new Wxpay(0, 'wechat_mweb');
        $res = $pay->queryByOutTradeNumber($orderId);
        $result = '支付取消' . $payLog['status'];
        if (isset($res['result_code']) && $res['result_code'] == 'SUCCESS') {
            if (in_array($res['trade_state'], ['SUCCESS', 'ACCEPT'])) {
                return View::fetch('success');
            }
            if (!empty($res['trade_state_desc'])) {
                $result = $res['trade_state_desc'];
            }
        }

        View::assign('message', $result);

        return View::fetch('failed');
    }
}
